package archer.back.controllers

import play.api.mvc.ControllerComponents
import utils._
import io.circe.syntax._
import cats.implicits._
import models.TableData
import org.xarcher.emiya.utils.EmbeddedServer
import play.api.libs.ws.WSClient

class UpdateController(
  controllerComponents: ControllerComponents,
  wsClient: WSClient,
  updateService: UpdateService)
  extends BackController(controllerComponents)
  with ArcherHelper {

  implicit val ec = defaultExecutionContext

  def list = Action.async { implicit request =>
    updateService.list.map(s => Ok(TableData(data = s).asJson))
  }

  def create(parentId: Int) = Action.async { implicit request =>
    updateService.create(parentId).map(s => Ok(TableData(data = s).asJson))
  }

  def update(id: Int, name: String) = Action.async { implicit request =>
    updateService.update(id, name).map(s => Ok(TableData(data = s).asJson))
  }

  def delete(id: Int) = Action.async { implicit request =>
    updateService.delete(id).map {
      case true => Ok(TableData(data = true).asJson)
      case false =>
        BadRequest(TableData(data = false, msg = "该节点仍有子节点未删除，不能执行删除操作").asJson)
    }
  }

  def moveNode(sourceId: Int, parentId: Int) = Action.async {
    implicit request =>
      updateService.moveNode(sourceId = sourceId, parentId = parentId).map {
        case true => Ok(TableData(data = true).asJson)
        case false =>
          BadRequest(TableData(data = false, msg = "没有发生移动操作").asJson)
      }
  }

  def callCrawl(parentId: Int) = Action.async { implicit request =>
    updateService
      .createCrawlAction(parentId = parentId)
      .map(s => Ok(TableData(data = s, msg = "启动抓取任务成功").asJson)) /*.map {
      case true => Ok(TableData(data = true).asJson)
      case false =>
        BadRequest(TableData(data = false, msg = "没有发生移动操作").asJson)
    }*/
  }

}
